package com.um.jdy.app.charge.scheduled;

import com.um.jdy.common.device.entity.po.Pile;
import com.um.jdy.common.device.enums.DeviceEnum;
import com.um.jdy.common.device.service.OnlineLogService;
import com.um.jdy.common.device.service.PileService;
import com.um.jdy.common.push.service.PushService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @author 甘天伟
 * @date 2022/2/20
 * 版权所有 广州优匠科技有限公司
 */
@Slf4j
@Component
@Profile({"!dev"})
public class DeviceStatusHeartTask {

    @Autowired
    PileService pileService;

    @Autowired
    OnlineLogService onlineLogService;

    @Autowired
    PushService pushService;

    /**
     * 设备心跳处理离线
     * 根据心跳时间来判断设备离线，每1分钟执行一次（首次为程序启动后30秒）
     */
    @Async
    @Scheduled(fixedRate = 60000, initialDelay = 30000)
    public void setOfflineByHeartime() {
        log.info("开始执行通过心跳时间使电瓶车设备离线定时任务 >>>>>>>>>>");

        List<Pile> pileList = pileService.getListBySqlName("get_heart_online_device_list", new String[]{});
        Pile updatePile = new Pile();
        pileList.stream().forEach(pile -> {
            updatePile.setDevicePileId(pile.getDevicePileId());
            updatePile.setDeviceStatus(DeviceEnum.DeviceStatus.Offline.name());
            updatePile.setLastOfflineTime(new Date());
            pileService.updateRow(updatePile);
            onlineLogService.addOffline(pile.getCode(),pile.getName());
            log.info("电瓶车设备[{}]心跳超时已离线", pile.getCode());

            // 推送
            pushService.pushDeviceOffline(pile);
        });
    }
}
